package org.buptsse.ui;

import org.buptsse.utils.APPConstant;
import org.buptsse.utils.ConnectionChecker;
import org.buptsse.utils.GloableInstance;
import org.buptsse.utils.MD5Helper;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;



//here i am
public class LoginActivity extends Activity {
	private final String LOGIN_URL = "login.do";
	
	private final static int OK=0;
	private final static int NOTOK=1;
//	private ProgressDialog mydialog;
	public static final int REF_LOGIN_RESULT = 1;
	private EditText etPass = null;
	private EditText etName = null;
	private Button btLogin = null;
	private ProgressBar waittingPB;
//	private ProgressBar footerProgressBarLayout;// 加载进度滚动条
	private String psw = "";
	CheckBox autoLoginCB;

	private ProgressDialog pDialog;
	SharedPreferences preferences = null;
	
	private Handler handler=new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			waittingPB.setVisibility(View.INVISIBLE);
			switch (msg.what) {
			case APPConstant.LoginFinish: {
				//Toast.makeText(getApplicationContext(), (String) msg.obj, 1000).show();
				CloudLearningApp cloudApp=(CloudLearningApp)getApplication();
				cloudApp.setUsername(etName.getText().toString());
				Intent intent=new Intent();
				intent.setClass(LoginActivity.this, MainCenterActivity.class);
				startActivity(intent);
				finish();
				break;
			}

			case APPConstant.LoginError: {
				Toast.makeText(getApplicationContext(), "用户名或密码错误", 1000).show();
				if(pDialog!=null)
					pDialog.dismiss();
				break;
			}
			}
		}
		
	};

	
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.login);
		etPass = (EditText) findViewById(R.id.password_edit);
		etName = (EditText) findViewById(R.id.username_edit);
		waittingPB=(ProgressBar) findViewById(R.id.waittingProgressBar);
		preferences = getSharedPreferences(APPConstant.PROJECT_NAME, Context.MODE_PRIVATE);
		autoLoginCB=(CheckBox) findViewById(R.id.auto_login_checkBox);
		// 设定TextView的标题文本
		TextView btRegister = (TextView) this.findViewById(R.id.register_link);
		btRegister.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//点击注册
				Intent it=new Intent(LoginActivity.this,RegisterActivity.class);
				LoginActivity.this.startActivity(it);
				finish();
			}
		});
		btLogin = (Button) this.findViewById(R.id.login_button);
		btLogin.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//点击登录
				String name=etName.getText().toString();
				String pwd=etPass.getText().toString();
				if(name.equals("") || pwd.equals(""))
				{
					Toast.makeText(getApplicationContext(), "请输入用户名和密码", 1000).show();
					return;
				}
				if(ConnectionChecker.isNetworkAvailable(getApplicationContext())==true)
				{
					if(loginThread==null || loginThread.IsRun()==false)
					{
						if(autoLoginCB.isChecked()==true)
						{
							//保存密码
							preferences.edit().putBoolean("autoLogin", true).commit();
							preferences.edit().putString("username", name).commit();
							preferences.edit().putString("pwd", MD5Helper.MD5Encoded(pwd)).commit();
							//preferences.edit().commit();
						}
						//waittingPB.setVisibility(View.VISIBLE);
						ShowWaittingDialog("正在登录");
						new Thread(new LoginThread(name, MD5Helper.MD5Encoded(pwd), handler)).start();
					}
				}else
				{
					Toast.makeText(getApplicationContext(), "网络连接不可用", 1000).show();
				}
				
			}
		});
		if(preferences.contains("autoLogin") && preferences.getBoolean("autoLogin", false)==true)
		{
			autoLoginCB.setChecked(true);
		}
		if(autoLoginCB.isChecked()==true)
		{
			if(preferences.contains("username")==true && preferences.contains("pwd")==true)
			{
				String username=preferences.getString("username", null);
				String pwd=preferences.getString("pwd", null);
				if(username!=null && pwd!=null)
				{
					//自动登录
					//waittingPB.setVisibility(View.VISIBLE);
					ShowWaittingDialog("正在登录");
					new Thread(new LoginThread(username, pwd, handler)).start();
				}
				else {
					autoLoginCB.setChecked(false);
				}
			}else {
				autoLoginCB.setChecked(false);
			}
		}
		
	}
	public void ShowWaittingDialog(String msg)
	{
		pDialog=new ProgressDialog(this);
		pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pDialog.setMessage(msg); 
        pDialog.show(); 
	}
	LoginThread loginThread=null;
	public class LoginThread implements Runnable
	{

		private Handler handler;
		private String name,pwd;
		private boolean isRun;
		
		public LoginThread(String name,String pwd,Handler handler)
		{
			this.handler=handler;
			this.name=name;
			this.pwd=pwd;
			isRun=false;
		}
		
		public boolean IsRun()
		{
			return isRun;
		}
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			isRun=true;
			String result=GloableInstance.user.login(name, pwd);
			//System.out.println("result is:"+result);
			if(result!=null && !result.contains("failure"))
			{
				//登录成功
				Message msg=handler.obtainMessage(APPConstant.LoginFinish);
				//result为a:b格式,a,b均为数字，a表示未读消息数，b表示未完成订单数
				msg.obj=result;
				handler.sendMessage(msg);
			}else
			{
				//登录失败
				Message msg=handler.obtainMessage(APPConstant.LoginError);
				handler.sendMessage(msg);
			}
			
			//lf
			isRun=false;
			//isRun = true;
		}
		
	}
}


